package com.jcfk.system.service;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.jcfk.system.domain.dto.SysNoticeFileDTO;
import com.jcfk.system.domain.dto.SysNoticeOrganDTO;
import com.jcfk.system.domain.dto.SysNoticeRoleDTO;
import com.jcfk.system.domain.po.*;
import com.jcfk.system.domain.query.SysNoticeFileQuery;
import com.jcfk.system.domain.query.SysNoticeOrganQuery;
import com.jcfk.system.domain.query.SysNoticeQuery;
import com.jcfk.system.domain.dto.SysNoticeDTO;
import com.jcfk.system.dao.SysNoticeDao;
import com.jcfk.common.business.service.BaseService;
import com.jcfk.common.web.domain.DataPage;
import com.jcfk.common.web.domain.RetResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jcfk.system.domain.query.SysNoticeRoleQuery;
import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;
import com.jcfk.common.core.utils.BeanUtils;
import cn.hutool.core.util.StrUtil;
import com.jcfk.common.security.utils.SecurityUtils;
import com.alibaba.druid.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

import java.util.Date;
import java.util.stream.Collectors;

/**
 * 
 *
 * @author awei
 * @email 522891237@gqq.com
 * @date 2023-11-24 09:54:15
 */
@Service
public class SysNoticeService extends BaseService<SysNoticeDao,SysNotice> {

    @Resource
    private SysNoticeRoleService sysNoticeRoleService;
    @Resource
    private SysNoticeOrganService sysNoticeOrganService;
    @Resource
    private SysNoticeFileService sysNoticeFileService;
    @Resource
    private SysNoticeReadRecordService sysNoticeReadRecordService;
    @Resource
    private SysUserService sysUserService;
    /**
     * SysNotice分页查询
     *
     * @param page  分页设置
     * @param query 查询条件
     * @return 分页查询结果
     */
    public DataPage<SysNoticeDTO> queryByPage(DataPage<SysNoticeDTO> page, SysNoticeQuery query) {
        // 分页查询
        page = this.baseMapper.queryByPage(page, query);
        return page;
    }

        /**
     * 判断SysNotice是已经存在
     *
     * @param dto
     * @return
     */
    public RetResult<String> isValid(SysNoticeDTO dto) {
        return RetResult.ok();
    }

    /**
     * 插入
     *
     * @param dto 插入对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public SysNoticeDTO insert(SysNoticeDTO dto) {

        // 保存
        SysNotice item = new SysNotice();
        BeanUtils.copyProperties(dto, item);
        this.setDefaultValue(item);
        item.setSentStatus(0);

        super.save(item);

        BeanUtils.copyProperties(item, dto);
        saveRelationshipTable(dto, item.getId());


        return dto;
    }

    /**
     * 更新
     *
     * @param dto 更新对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public SysNoticeDTO update(SysNoticeDTO dto) {

        // 保存
        SysNotice item = new SysNotice();
        BeanUtils.copyProperties(dto, item);

        // 默认数据
        this.setDefaultValue(item);

        super.updateById(item);
        saveRelationshipTable(dto, item.getId());
        BeanUtils.copyProperties(item, dto);

        return dto;
    }

    // 保存关联关系
    private void saveRelationshipTable(SysNoticeDTO dto, String noticeId){
        saveNoticeRole(dto, noticeId);
        saveNoticeOrgan(dto, noticeId);
        saveNoticeFile(dto, noticeId);
    }

    // 与角色关联关系
    private void saveNoticeRole(SysNoticeDTO dto, String noticeId){
        sysNoticeRoleService.remove(Wrappers.<SysNoticeRole>lambdaQuery().eq(SysNoticeRole::getNoticeId, noticeId));
        List<SysNoticeRole> roleList = dto.getRoleIds().stream().map((roleId) -> {
            SysNoticeRole sysNoticeRole = new SysNoticeRole();
            sysNoticeRoleService.setDefaultValue(sysNoticeRole);
            sysNoticeRole.setRoleId(roleId);
            sysNoticeRole.setNoticeId(noticeId);
            return sysNoticeRole;
        }).collect(Collectors.toList());
        sysNoticeRoleService.saveBatch(roleList);
    }
    // 与组织关联关系
    private void saveNoticeOrgan(SysNoticeDTO dto, String noticeId){
        sysNoticeOrganService.remove(Wrappers.<SysNoticeOrgan>lambdaQuery().eq(SysNoticeOrgan::getNoticeId, noticeId));
        List<SysNoticeOrgan> organList = dto.getOrganizationIds().stream().map((organId) -> {
            SysNoticeOrgan sysNoticeOrgan = new SysNoticeOrgan();
            sysNoticeOrganService.setDefaultValue(sysNoticeOrgan);
            sysNoticeOrgan.setOrganizationId(organId);
            sysNoticeOrgan.setNoticeId(noticeId);
            return sysNoticeOrgan;
        }).collect(Collectors.toList());
        sysNoticeOrganService.saveBatch(organList);
    }
    // 与附件关联关系
    private void saveNoticeFile(SysNoticeDTO dto, String noticeId){
        sysNoticeFileService.remove(Wrappers.<SysNoticeFile>lambdaQuery().eq(SysNoticeFile::getNoticeId, noticeId));
        List<SysNoticeFile> fileList = dto.getFiles().stream().map((file) -> {
            SysNoticeFile sysNoticeFile = new SysNoticeFile();
            sysNoticeFileService.setDefaultValue(sysNoticeFile);
            sysNoticeFile.setNoticeId(noticeId);
            sysNoticeFile.setFileType(file.getFileType());
            sysNoticeFile.setPath(file.getPath());
            sysNoticeFile.setOriginalFilename(file.getOriginalFilename());
            sysNoticeFile.setFilename(file.getFilename());
            sysNoticeFile.setUrl(file.getUrl());
            return sysNoticeFile;
        }).collect(Collectors.toList());
        sysNoticeFileService.saveBatch(fileList);
    }
    /**
     * 根据批量主键删除(逻辑删除)
     *
     * @param dto
     * @return bool
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean logicDeleteList(SysNoticeDTO dto) {

        SysNotice item = new SysNotice();

        this.setDefaultValue(item);
        item.setVersion(dto.getVersion());
        item.setDeleted(1);

        QueryWrapper<SysNotice> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", dto.getIds());

        return this.update(item, queryWrapper);
    }

    /**
     * 设置添加默认值
     *
     * @param item 添加对象
     */
    public void setDefaultValue(SysNotice item) {
        if (StrUtil.isEmpty(item.getCreatedUserId())) {
            item.setCreatedUserId(SecurityUtils.getUserId());
            item.setCreateTime(new Date());
            item.setCreatedUserName(SecurityUtils.getUserName());
        }
        item.setLastUpdatedUserId(SecurityUtils.getUserId());
        item.setLastUpdateTime(new Date());
        item.setDeleted(0);
        item.setLastUpdatedUserName(SecurityUtils.getUserName());
    }

    /**
     * 根据主键获取信息
     *
     * @param id 主键
     * @return StandardCodeDTO
     */
    public SysNoticeDTO get(Long id) {
        // 查询数据
        SysNotice item = this.baseMapper.selectById(id);
            SysNoticeDTO dto = new SysNoticeDTO();
        try {
            BeanUtils.copyProperties(item, dto);
            // 查询关联角色
            SysNoticeRoleQuery roleQuery = new SysNoticeRoleQuery();
            roleQuery.setNoticeId(item.getId());
            List<SysNoticeRoleDTO> roleDTOList = sysNoticeRoleService.getList(roleQuery);
            dto.setRoles(roleDTOList);
            dto.setRoleIds(roleDTOList.stream().map(SysNoticeRoleDTO::getRoleId).collect(Collectors.toList()));
            // 查询关联组织
            SysNoticeOrganQuery organQuery = new SysNoticeOrganQuery();
            organQuery.setNoticeId(item.getId());
            List<SysNoticeOrganDTO> organDTOList = sysNoticeOrganService.getList(organQuery);
            dto.setOrganizations(organDTOList);
            dto.setOrganizationIds(organDTOList.stream().map(SysNoticeOrganDTO::getOrganizationId).collect(Collectors.toList()));
            // 查询关联附件
            SysNoticeFileQuery fileQuery = new SysNoticeFileQuery();
            fileQuery.setNoticeId(item.getId());
            List<SysNoticeFileDTO> fileDTOList = sysNoticeFileService.getList(fileQuery);
            dto.setFiles(fileDTOList);
        } catch (RuntimeException e) {
            throw e;
        }

        return dto;
    }

    /**
     * 发布通知
     * @param sysNoticeDto 发布通知信息
     */
    @Transactional
    public void send(SysNoticeDTO sysNoticeDto) {
        sysNoticeDto.setSentStatus(1);
        sysNoticeDto.setSentTime(new Date());
        sysNoticeDto.setSentUserId(SecurityUtils.getUserId());
        // 保存
        SysNotice item = new SysNotice();
        BeanUtils.copyProperties(sysNoticeDto, item);
        this.baseMapper.updateById(item);
        List<SysUser> userList = sysUserService.queryUsersByOrganAndRole(sysNoticeDto.getOrganizationIds(),sysNoticeDto.getRoleIds());
        List<SysNoticeReadRecord> recordList = userList.stream()
                .map(user -> {
                    SysNoticeReadRecord record = new SysNoticeReadRecord();
                    record.setNoticeId(sysNoticeDto.getId());
                    record.setReaderId(user.getId());
                    record.setReadStatus(0);
                    sysNoticeReadRecordService.setDefaultValue(record);
                    return record;
                }).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(recordList))
            sysNoticeReadRecordService.saveBatch(recordList);
    }
}

